import { useEffect, useState, forwardRef } from 'react';
import { useDispatch, useSelector } from 'react-redux';
import loadable from '@loadable/component';
import { App } from 'antd';

import { HOME } from '@/config/url';
import { getWxPayQrCode } from '@/service/pay';
import { isWx, isMobileDevice } from '@/utils';

const IconFont = loadable(() => import('@/components/IconFont'));
const Dialog = loadable(() => import('@/components/Dialog'));
const WxQrCode = loadable(() => import('./WxQrCode'));

import styles from './index.module.scss';

export default forwardRef((props, ref) => {
    const [status, setStatus] = useState('');
    const [open, setOpen] = useState(false);
    const dispatch = useDispatch();
    const { userInfo={} } = useSelector(s => s.common);
    const { message } = App.useApp();
    const { payInfo={}, onOk, onCancel } = props;
    const {price, ...rest} = payInfo || {};

    const toGetOpenId = () => {
        const redirect_uri = encodeURIComponent(location.href);
        const appId = 'wxc59a674315a09529';

        // 如果是微信公众号
        window.location.href =
            'https://open.weixin.qq.com/connect/oauth2/authorize?appid=' +
            (appId || '') +
            '&redirect_uri=' +
            redirect_uri +
            '&response_type=code&scope=snsapi_userinfo&state=1#wechat_redirect';
    };
    // 拉起公众号支付
    const onBridgeReady = (data={}) => {
        let postData = {
            "appId": data.appId, //公众号名称，由商户传入
            "timeStamp": data.timeStamp, //时间戳，自1970年以来的秒数
            "nonceStr": data.nonceStr, //随机串
            "package": data.package,
            "signType": data.signType, //微信签名方式：
            "paySign": data.paySign //微信签名
        };
        WeixinJSBridge.invoke(
            'getBrandWCPayRequest',
            postData,
            function(res) {
                // 拉起支付后就清除自动支付标志，TODO

                if (res.err_msg == "get_brand_wcpay_request:ok") {
                    // 使用以上方式判断前端返回,微信团队郑重提示：
                    //res.err_msg将在用户支付成功后返回ok，但并不保证它绝对可靠。

                    // 记录需要弹客服弹框
                    // window?.location.reload();
                    location.href = HOME;
                }else if (res.err_msg == "get_brand_wcpay_request:cancel") {
                    // 处理成支付失败
                    console.log(`取消支付`);
                    location.href = HOME;
                }else if(res.err_msg == "get_brand_wcpay_request:fail") {
                    // 处理成支付失败
                    console.log(`支付失败`);
                    location.href = HOME;
                }
            }
        );
    }
    // 去支付
    const payWithVx = () => {
        // WeixinJSBridge不存在 或者 不是微信环境 或者不是移动设备，都用弹框支付
        if (typeof WeixinJSBridge == "undefined" || !isWx() || !isMobileDevice()) {
            setOpen(true);
        } else {
            // 这里需要有这么一个逻辑，如果是移动端微信环境，那么就自动静默登录一下（但是这个应用有点扯，微信登录必须强绑手机号）
            // 微信公众号支付，要求用户必须**关注**公众号才能使用，需要openId
            // classify, type, productId, productNum, memberCouponIds,

            if(!userInfo.accountOpenId) return toGetOpenId(); // 就是为了获取openId

            let formData = new FormData();
            formData.append('type', 2);
            for(let key in rest) {
                formData.append(key, rest[key]);
            }

            getWxPayQrCode(formData).then(response => {
                if(0 === response?.code) {
                    if (typeof WeixinJSBridge === "undefined") {
                        if (document.addEventListener) {
                            document.addEventListener('WeixinJSBridgeReady', onBridgeReady(response?.data), false);
                        } else if (document.attachEvent) {
                            document.attachEvent('WeixinJSBridgeReady', onBridgeReady(response?.data));
                            document.attachEvent('onWeixinJSBridgeReady', onBridgeReady(response?.data));
                        }
                    } else {
                        onBridgeReady(response?.data);
                    }
                }else{
                    message.warning(response?.msg || response?.message || '数据异常，请稍后重试');
                    localStorage.removeItem('_invitation_payed_vip_type');
                    localStorage.removeItem('_redirect');
                }
            }).catch(e => {
                message.error(e?.msg || e?.message || '数据异常，请稍后重试。');
                localStorage.removeItem('_invitation_payed_vip_type');
                localStorage.removeItem('_redirect');
            });
        }
    };

    // 确定
    const payOk = () => {
        setOpen(false);
        onOk();
    };
    // 有问题，联系客服
    const payError = () => {
        setOpen(false);
        // props.onCancel();

        onOk();
    };
    const closeDialog = () => {
        setOpen(false);
    };

    useEffect(() => {
        return () => {
            setStatus('');
            setOpen(false);
        }
    }, []);

    return (
        <div className={styles['container']}>
            {
                props.children ?
                    <div onClick={payWithVx} ref={ref}>{props.children}</div>
                    :
                    <button onClick={payWithVx} ref={ref}>确认办理</button>
            }

            <Dialog
                rootClassName={styles['dialog']}
                open={open || false}
                closeable={false}
                maskClosable={false}
                header=""
                onCancel={e => {closeDialog();onCancel();}}
                onOk={e => {closeDialog();onOk()}}
                footer=""
                width={360}
                destroyOnHidden={true}
            >
                <div className={styles['content']}>
                    <div className={styles['header']}>
                        <span className=''><IconFont name="icon-disanfang-weixin" /></span>
                        微信扫码支付
                    </div>
                    <div className={styles['qr']}>
                        <div className={styles['img']}>
                            <WxQrCode {...props} callback={s => setStatus(s)}/>
                        </div>
                    </div>

                    {
                        0 === status ?
                            <div className={styles['tips']}>已扫码，待支付</div>
                            :
                            (
                                1 === status || 2 === status ?
                                    <div className={styles['footer']}>
                                        <button onClick={payOk} className={styles['ok']}>支付完成</button>
                                        <button onClick={payError} className={styles['err']}>支付遇到问题</button>
                                    </div>
                                    :
                                    null
                            )
                    }
                </div>
            </Dialog>
        </div>
    )
});